package com.yiyibook.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yiyibook.entity.OrderHead;
import com.yiyibook.entity.OrderLine;
import com.yiyibook.entity.ShoppingCar;
import com.yiyibook.service.OrderHeadService;
import com.yiyibook.service.OrderLineService;
import com.yiyibook.service.ShoppingCarService;
import com.yiyibook.util.Msg;
import com.yiyibook.util.OrderNumber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单头信息 Controller
 *
 * @author yi.wu
 * @date 2019-10-14
 */
@RestController
@RequestMapping("/orderHeader")
public class OrderHeadController {

    @Autowired
    private OrderHeadService orderHeadService;

    @Autowired
    private OrderLineService orderLineService;

    @Autowired
    private ShoppingCarService shoppingCarService;

    @PostMapping("/insert")
    public Msg insert(@RequestBody List<ShoppingCar> shoppingCars){
        OrderHead orderHead = new OrderHead();
        orderHead.setMemberId(shoppingCars.get(0).getMemberId());
        // TODO: 2019/10/15 生成订单编码
        // 获取数据库中最后一次的订单编号
        OrderHead oh = orderHeadService.selectLast();
        if(oh!=null){
            orderHead.setOrderHeadNumber(OrderNumber.setOrderNumber(oh.getOrderHeadNumber()));
        }else {
            orderHead.setOrderHeadNumber(OrderNumber.setOrderNumber(null));
        }
        // 生成订单头，并返回主键
        OrderHead i = orderHeadService.insert(orderHead);
        // 生成订单行
        for(ShoppingCar shoppingCar : shoppingCars){
            OrderLine orderLine = new OrderLine();
            orderLine.setOrderHeadId(i.getOrderHeadId());
            orderLine.setBookId(shoppingCar.getBookId());
            orderLine.setBookUnitPrice(shoppingCar.getBookUnitPrice());
            orderLine.setBookBuyQuantity(shoppingCar.getBookBuyQuantity());
            orderLine.setLineAmount(shoppingCar.getBookTotalAmount());
            orderLineService.insert(orderLine);
            // 删除购物车
            shoppingCarService.deleteById(shoppingCar.getShopCarId());
        }
        return Msg.success().add("success","生成订单成功！");
    }

    @GetMapping("getAll")
    public Msg getAll(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum){
        PageHelper.startPage(pageNum,10);
        List<OrderHead> orderHeads = orderHeadService.selectAll();
        //传入连续显示的页数
        PageInfo page = new PageInfo(orderHeads,5);
        for(OrderHead orderHead : orderHeads){
            List<OrderLine> orderLines = orderLineService.selectByHeadId(orderHead.getOrderHeadId());
            orderHead.setOrderLines(orderLines);
        }
        return Msg.success().add("pageInfo",page);
    }
}
